<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="菜单权限管理"></n-card>
    </div>
    <n-grid class="mt-4" cols="1 s:1 m:1 l:3 xl:3 2xl:3" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: true }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-dropdown trigger="hover" @select="selectAddMenu" :options="addMenuOptions">
                <n-button ghost icon-placement="right">
                  添加菜单
                  <template #icon>
                    <div class="flex items-center">
                      <n-icon size="14">
                        <DownOutlined />
                      </n-icon>
                    </div>
                  </template>
                </n-button>
              </n-dropdown>
              <n-button ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
              <n-button type="primary" :loading="btnLoading" :on-click="refreshSysMenuApi">
              <template #icon>
                <n-icon>
                  <SyncOutlined />
                </n-icon>
              </template>
              刷新资源池
            </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="input" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="treeLoading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree block-line cascade checkable :virtual-scroll="true" :pattern="pattern" :data="treeData"
                  :expandedKeys="expandedKeys" style="max-height: 570px; overflow: hidden"
                  @update:selected-keys="selectedTree" @update:expanded-keys="onExpandedKeys" />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="2">
        <n-card :segmented="{ content: true }" :bordered="false" size="small" style="max-height: 710px;">
          <template #header>
            <n-space>
              <n-icon size="18">
                <FormOutlined />
              </n-icon>
              <span>编辑菜单{{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
            </n-space>
          </template>
          <n-alert type="info" closable> 从菜单列表选择一项后，进行编辑</n-alert>
          <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="100"
            v-if="isEditMenu" class="py-4">
            <n-grid :cols="24" :x-gap="24">
              <n-form-item-gi :span="12" label="菜单类型" path="menuType">
                <n-select v-model:value="formParams.menuType" filterable placeholder="请选择类型" :options="menuOptions" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="菜单名称" path="name">
                <n-input maxlength="200" show-count placeholder="请输入菜单名称" v-model:value="formParams.name" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="菜单路径" path="path">
                <n-input maxlength="200" show-count placeholder="请输入菜单路径" v-model:value="formParams.path" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="打开方式" path="openType">
                <n-radio-group v-model:value="formParams.openType" name="radiogroup">
                  <n-space>
                    <n-radio :value="1">当前窗口</n-radio>
                    <n-radio :value="2">新窗口</n-radio>
                  </n-space>
                </n-radio-group>
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="菜单权限" path="auth">
                <n-input maxlength="100" show-count placeholder="请输入权限，多个权限用，分割" v-model:value="formParams.auth" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="是否隐藏" path="hidden">
                <n-select v-model:value="formParams.hidden" filterable placeholder="请选择是否隐藏" :options="hiddenOptions" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="获取方式" path="method">
                <n-select v-model:value="formParams.method" filterable placeholder="请选择获取方式" :options="methodOptions" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="所属服务" path="serviceId">
                <n-select v-model:value="formParams.serviceId" filterable placeholder="请选择所属服务"
                  :options="serviceOptions" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="菜单排序" path="orderNum">
                <n-input-number style="width: 100%;" placeholder="请输入排序" v-model:value="formParams.orderNum" />
              </n-form-item-gi>
              <n-form-item-gi :span="12" label="菜单描述" path="description">
                <n-input maxlength="300" show-count type="textarea" :autosize="{
                  minRows: 3,
                  maxRows: 5
                }" v-model:value="formParams.description" filterable placeholder="请输入描述" />
              </n-form-item-gi>
              <n-form-item-gi :span="24" style="margin-left: 100px">
                <n-space>
                  <n-button type="primary" :loading="subLoading" @click="formSubmit">保存修改</n-button>
                  <n-button @click="handleDel">删除</n-button>
                </n-space>
              </n-form-item-gi>
            </n-grid>
          </n-form>
        </n-card>
      </n-gi>
    </n-grid>
    <CreateDrawer ref="createDrawerRef" :title="drawerTitle" :parentId="selectParentId" :methodOptions="methodOptions"
      :serviceOptions="serviceOptions" :reloadMenuTree="reloadMenuTree"/>
  </div>
</template>
<script lang="ts" setup>
import { ref, unref, reactive, onMounted, computed } from 'vue';
import { useDialog, useMessage } from 'naive-ui';
import { DownOutlined, AlignLeftOutlined, SearchOutlined, FormOutlined,SyncOutlined } from '@vicons/antd';
import { getMenuList, updateMenu, menuInfo, delSysMenu,refreshSysMenu } from '@/api/system/menu';
import { dictGroup } from '@/api/system/dict';
import CreateDrawer from './CreateDrawer.vue';
import { ResultEnum } from '@/enums/httpEnum';
import { hiddenOptions, menuOptions } from '@/utils/convert';
const btnLoading = ref(false);
const rules = {
  name: {
    required: true,
    message: '请输入菜单名称',
    trigger: 'blur',
  },
  path: [
    {
      required: true,
      message: '请输入路径',
      trigger: 'blur',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  menuType: {
    required: true,
    message: '请选择菜单类型',
    trigger: ['blur', 'change'],
  },
  auth: [
    {
      required: true,
      message: '请输入权限标识',
      trigger: 'blur',
    },
    { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
  ],
  method: {
    required: true,
    message: '请选择获取方式',
    trigger: ['blur', 'change'],
  },
  serviceId: {
    required: true,
    message: '请选择所属服务',
    trigger: ['blur', 'change'],
  },
  orderNum: {
    type: 'number',
    required: true,
    message: '请输入排序',
    trigger: ['blur', 'change'],
  },
};

const formRef: any = ref(null);
const createDrawerRef = ref();
const message = useMessage();
const dialog = useDialog();
const subLoading = ref(false);
let treeItemKey = ref([]);
const methodOptions = ref([]);
const serviceOptions = ref([]);
let expandedKeys = ref([]);

const treeData = ref([]);

const treeLoading = ref(true);
const isEditMenu = ref(false);
const treeItemTitle = ref('');
const pattern = ref('');
const drawerTitle = ref('');
const selectParentId = ref(0);
const isAddSon = computed(() => {
  return !treeItemKey.value.length;
});

const addMenuOptions = ref([
  {
    label: '添加顶级菜单',
    key: 'home',
    disabled: false,
  },
  {
    label: '添加子菜单',
    key: 'son',
    disabled: isAddSon,
  },
]);

let formParams = reactive({
  auth: '',
  description: '',
  hidden: false,
  id: 0,
  menuType: '',
  method: '',
  name: '',
  openType: 1,
  orderNum: 1,
  parentId: 0,
  path: '',
  serviceId: ''
});

function selectAddMenu(key: string) {
  drawerTitle.value = key === 'home' ? '添加顶栏菜单' : `添加子菜单：${treeItemTitle.value}`;
  if (key === 'home') {
    selectParentId.value = 0;
  }
  openCreateDrawer();
}

function openCreateDrawer() {
  const { openDrawer } = createDrawerRef.value;
  openDrawer();
}

async function selectedTree(keys) {
  if (keys.length) {
    const treeItem = await menuInfo({ id: keys[0] });
    selectParentId.value = keys[0];
    treeItemKey.value = keys;
    treeItemTitle.value = treeItem.name;
    Object.assign(formParams, treeItem);
    isEditMenu.value = true;
  } else {
    isEditMenu.value = false;
    treeItemKey.value = [];
    treeItemTitle.value = '';
  }
}

function handleDel() {
  dialog.warning({
    title: '警告',
    content: `您确定想删除此权限吗?`,
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: async () => {
      const data = await delSysMenu({ id: formParams.id });
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        reloadMenuTree();
      }
    },
  });
}

function formSubmit(e: MouseEvent) {
  e.preventDefault();
  formRef.value.validate(async (errors) => {
    if (!errors) {
      subLoading.value = true;
      const data = await updateMenu(formParams);
      if (data.code !== ResultEnum.SUCCESS) {
        const resultMsg = data.data ? data.data : '';
        message.error(data.mesg + '-' + resultMsg);
      }
      if (data.code === ResultEnum.SUCCESS) {
        message.success(data.mesg);
        isEditMenu.value = false;
        reloadMenuTree();
        resetFrom();
      }
      subLoading.value = false;
    } else {
      message.error('请填写完整信息');
    }
    subLoading.value = false;
  });
}

function resetFrom() {
  formParams = Object.assign(formParams, {
    auth: '',
    description: '',
    hidden: false,
    id: null,
    menuType: '',
    method: '',
    name: '',
    openType: null,
    orderNum: null,
    parentId: null,
    path: '',
    serviceId: ''
  });
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = unref(treeData).map((item: any) => item.key as string) as [];
  }
}
/**
 * 访问请求方式
 */
async function getMethodOptions() {
  const data = await dictGroup({ dictGroup: 'http_method' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  methodOptions.value = arry;
}
/**
 * 服务列表
 */
async function getServiceOptions() {
  const data = await dictGroup({ dictGroup: 'server_list' });
  const arry = data.map(item => ({ label: item.dictName, value: item.dictValue }));
  serviceOptions.value = arry;
}
/**
 * 初始化菜单树
 */
async function reloadMenuTree(){
  treeLoading.value = true;
  const treeMenuList = await getMenuList({});
  treeData.value = treeMenuList;
  treeLoading.value = false;
}
/**
 * 刷新菜单-资源池
 */
const refreshSysMenuApi = () => {
  btnLoading.value = true;
  setTimeout(async () => {
    const data = await refreshSysMenu();
    if (data.code !== ResultEnum.SUCCESS) {
      const resultMsg = data.data ? data.data : '';
      message.error(data.mesg + '-' + resultMsg);
    }
    if (data.code === ResultEnum.SUCCESS) {
      message.success(data.mesg);
    }
    btnLoading.value = false;
  }, 500);
}
onMounted(async () => {
  const treeMenuList = await getMenuList({});
  treeData.value = treeMenuList;
  treeLoading.value = false;
  getMethodOptions();
  getServiceOptions();
});

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
}
</script>
